#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <functional>
#include <unordered_map>
#include "Protocol.hpp"

static const uint16_t gport = 8080;
static const int gbacklog = 5;

namespace server
{
    class HttpServer
    {
        typedef std::function<bool(const HttpRequest &, HttpResponse &)> func_t;

        enum
        {
            USAGE_ERR = 1,
            SOCK_ERR,
            BIND_ERR,
            LISTEN_ERR
        };

    public:
        HttpServer(func_t func, const uint16_t &port = gport) : _func(func), _listensock(-1), _port(port)
        {
        }
        void initServer()
        {
            // signal(SIGCHLD, SIG_IGN);
            // 1. 创建套接字
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock == -1)
            {
                exit(SOCK_ERR);
            }

            // 2.绑定自己的网络信息
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;
            if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                exit(BIND_ERR);
            }

            // 3. 设置socket 为监听状态
            if (listen(_listensock, gbacklog) < 0) // gbacklog后面再学
            {
                exit(LISTEN_ERR);
            }
        }
        void registerCb(std::string servicename, func_t cb)
        {
            _funcs.insert(make_pair(servicename, cb));
        }
        void HandlerHttp(int sock)
        {
            char buffer[4096];
            HttpRequest req;
            HttpResponse resp;
            size_t n = recv(sock, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] == 0;
                req.inbuffer = buffer;
                req.parse();
                // if(_funcs.find(req.path) == _funcs.end()) return;
                // _funcs[req.path](req, resp);
                _func(req, resp);
                send(sock, resp.outbuffer.c_str(), resp.outbuffer.size(), 0);
            }
        }
        void start()
        {
            for (;;)
            {
                // 4. 获取新链接
                // sock, 和client进行通信的fd
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
                if (sock < 0)
                {
                    continue;
                }

                // version 2 // 多进程版(2)
                pid_t id = fork();
                if (id == 0)
                {
                    // 关闭不需要的文件描述符
                    close(_listensock);
                    if (fork() > 0)
                        exit(0);
                    HandlerHttp(sock);
                    close(sock);
                    exit(0);
                }
                // father
                waitpid(id, nullptr, 0);
            }
        }
        ~HttpServer()
        {
        }

    private:
        int _listensock; // 不是用来通信的, 而是用来监听链接的, 获取新链接
        uint16_t _port;
        func_t _func;

        std::unordered_map<std::string, func_t> _funcs;
    };
};